<?php
namespace Swiftx\System;
use Swiftx\Http\IRequest;
use Swiftx\Http\ISession;
use Swiftx\Tools\Debug;

/**
 * 系统主控类
 *
 * @author		Hismer <odaytudio@gmail.com>
 * @since		2014-04-26
 * @copyright	Copyright (c) 2014-2015 Swiftx Inc.
 *
 * @property ISession $Session
 * @property IRequest $Request
 *
 * @package    Swiftx\System
 *
 */
class Core {

    /** @var Config 系统配置 */
    protected $config = null;
    /** @var ISession Session对象 */
    protected static $_session;
    /** @var IRequest Request对象 */
    protected static $_request;

    /**
     * 系统构造
     * @param Config $config
     */
    protected function __construct(Config $config){
        $this->config = $config;
    }

    /**
     * 主引导程序
     */
    final public static function Bootstrap(){
        defined('DS') or define('DS', DIRECTORY_SEPARATOR);         // 定义分界符
        static::RegisterNamespace('Swiftx',dirname(__DIR__).DS);   // 注册命名空间
    }

    /**
     * 系统初始化
     * @param Config $config
     */
    final public static function Init(Config $config){
        $classname = $config->SessionDriver;
        static::$_session = new $classname();
        $classname = $config->RequestDriver;
        static::$_request = new $classname();
        if($config->Debug) Debug::Init($config->DebugOut, static::$_request);
        if($config->AutoRun) {
            $classname = static::class;
            /** @var static $system */
            $system = new $classname($config);
            try{
                $system->Main(static::$_session, static::$_request);
            } catch (\Exception $event) {
                $system->Exception($event, static::$_request);
            }
        }
    }

    /**
     * 系统主函数
     * @param ISession $session
     * @param IRequest $request
     * @return void
     */
    public function Main($session, $request){

    }

    /**
     * 发生异常处理
     * @param \Exception $event
     * @throws \Exception
     */
    public function Exception(\Exception $event){
        throw $event;
    }

    /**
     * 注册命名空间
     * @param string $name
     * @param string $dir
     */
    final public static function RegisterNamespace($name, $dir){
        spl_autoload_register(function($classname) use ($name, $dir){
            $name_length = strlen($name.='\\');
            if(substr($classname,0,$name_length) != $name) return;
            $classfile = $dir.strtr(substr($classname,$name_length),'\\',DS).'.class.php';
            if(!file_exists($classfile)) return;
            /** @noinspection PhpIncludeInspection */
            require $classfile;
            if(method_exists($classname, '__static')) $classname::__static();
        });
    }

}